package com.zrrd.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.reggie.bean.Category;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    //分页查询
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        //创建分页对象
        Page pageInfo = new Page(page,pageSize);
        //创建条件构造器
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("sort");
        //执行分页查询
        categoryService.page(pageInfo,wrapper);
        return R.success(pageInfo);
    }

    //添加分类
    @PostMapping
    private R<String> add(@RequestBody Category category){
        //执行保存
        return categoryService.save(category) == true ? R.success("添加成功") : R.error("添加失败");

    }

    //修改分类
    @PutMapping
    private R<String> update(@RequestBody Category category){
        return categoryService.updateById(category) == true ? R.success("修改成功") : R.error("修改失败");

    }

    //删除分类
    @DeleteMapping
    private R<String> delete(Long id){
        return categoryService.removeById(id) == true ? R.success("删除成功") : R.error("删除失败");
    }


    //根据类型查询分类（type=1：菜品 type=2：套餐）
    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        //条件构造器
        QueryWrapper<Category> wrapper = new QueryWrapper<>();

        //如果type不为空
        if (type != null){
            wrapper.eq("type",type);
        }


        //查询
        List<Category> list = categoryService.list(wrapper);
        //返回
        return R.success(list);
    }
}
